package tech.aistar.controller.daoyou;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tech.aistar.config.GuidelInterceptor;


import tech.aistar.entity.authordis.UserTable;
import tech.aistar.entity.daoyou.*;


import tech.aistar.entity.person_center.Orders;
import tech.aistar.mapper.guidemapper.Guide;
import tech.aistar.util.IdWorker;
import tech.aistar.util.Random_util;
import tech.aistar.util.SmsModel;
import tech.aistar.util.date_SimpleDateFormat.DateUtileDemo;

import tech.aistar.service.daoyou.GuideService;

import tech.aistar.util.mytoken.CreatToken;
import tech.aistar.vo.daoyou.GuideIndex;
import tech.aistar.vo.daoyou.MyOrders;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/guide")
public class guideIndices {


    @Autowired
    private GuideService guideService;

    @Autowired
    private IdWorker worker;


    @RequestMapping("/index")
    public String getPages(){
        return "Tourist/travels_index";
    }



//    查看游记
    @RequestMapping("/page")
    public String getIndex(Model model,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "6") Integer pageSize){


        Map<String,Object> map=guideService.getallPersons(pageNum,pageSize);

        PageInfo<GuideInfo>guideInfoPageInfo = (PageInfo<GuideInfo>) map.get("guideInfoPageInfo");

        Set<GuideIndex> guideIndices= (Set<GuideIndex>) map.get("guideIndices");



        model.addAttribute("guideInfoPageInfo",guideInfoPageInfo);

//        Set<GuideIndex> guideIndices=guideService.getAllPerson();
        model.addAttribute("information",guideIndices);
//        Iterator<GuideIndex> i=guideIndices.iterator();

        return "Tourist/travel_indexPage";
    }


    //查看个人主页
    @RequestMapping("/getperson/{id}")///
    public  String getPersonById(@PathVariable("id") Integer id,Model model,HttpServletRequest request){

//        HttpSession session=request.getSession();

        GuideIndex guideIndex= guideService.getPerosonById(id);
        UserTable userTable= guideService.getuserByGuideId(id);
        //

        //查询线路 --  391行
        GuideRoute guideRoute = guideService.selectRouteByid(id);
        model.addAttribute("guideRoute",guideRoute);

        model.addAttribute("guideIndex",guideIndex);
        model.addAttribute("headImg",userTable.getHeadImg());


//        UserTable userTable1s= (UserTable) session.getAttribute("userId");
//        model.addAttribute("u",userTable1s.getId());
//        model.addAttribute("headImg",userTable1s.getHeadImg());
//
        return  "Tourist/reservation";
    }
    //查看个人主页评论的分页

    @RequestMapping("/getpage/{id}")//
    public  String getPage(@PathVariable("id") Integer id,Model model,HttpServletRequest request,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "3") Integer pageSize){

        System.out.println(pageNum+"pageNum");
        System.out.println(pageSize+"pageSize");
        PageInfo<GuidePageCommen> pageInfo= guideService.GuideCommentPage(pageNum,pageSize,id);

        request.setAttribute("CommonPage",pageInfo);
        return  "Tourist/commonPage";
    }


//    预约功能

    /**
     * 先查看用户是否登陆
     * 查看用户是否已经实名认证
     * 如果实名验证以后再进去跳转
     * @param request
     * @return
     */


    //身份认证页面
    @RequestMapping("/application")
    public  String getApplication(HttpServletRequest request){
        return "redirect:/guide";
    }


    //预约导游的事件  需要修改
    /*
    不能是导游自己本人预约自己
     */
    //要看导游是否有时间       d_id}/
    @RequestMapping ("/reservation/{dao_id}")//获取道的是导游的id
    @GuidelInterceptor
//    @PathVariable("d_id") Integer d_id,
    public String getReservation(HttpServletRequest request, Model model,  @PathVariable("dao_id")Integer dao_id, HttpServletResponse response){
        HttpSession session= request.getSession();
        UserTable userTable = (UserTable) session.getAttribute("userId");

//        查询线路 --  391行
        GuideRoute guideRoute = guideService.selectRouteByid(dao_id);
        model.addAttribute("guideRoute",guideRoute);

        //检测是否实名
             if(userTable.getIdcard().length()==18){
                 GuideInfo apply= guideService.checkApply(userTable.getId());
                 //自己不能申请自己
             if(apply!=null&&apply.getId()==dao_id){
                 return    "redirect:/guide/index";
             }
                 GuideIndex guideIndex= guideService.getPerosonById(dao_id);
                 //状态=0 才是可以接客的状态
                 if(guideIndex.getGuideInfo().getStatus()==0){

                     request.setAttribute("d_id",userTable.getId());
//                     request.setAttribute("d_id",d_id);
                     model.addAttribute("daoyou",dao_id);
                     //短信通知

                     return  "Tourist/Order";
                 }else{
                     System.out.println("导游不可以接单");
                     //如果该导游不能接单 就不可以 状态不可以
                   return "redirect:/guide/getperson/"+dao_id ;
                 }
             }else{

                 //跳转到实名
                 return  "Tourist/applyTouristService";
             }
    }



//    inserPhoto
    @PostMapping("/addphoto")
    @GuidelInterceptor
public @ResponseBody GuideResult addphoto(String photo,HttpServletRequest request){
        HttpSession session=request.getSession();
        Integer ids= (Integer) session.getAttribute("daoyou_id");
try{
    guideService.inserPhoto(ids,photo);
    return new GuideResult(GuideCodeStatus.OK,true,"成功");
}catch (Exception e){
    return new GuideResult(GuideCodeStatus.ERROR,false,"内部错误");
}

    }


//问题:
    /**
     * 防止重复提交表单 配置拦截器
     * @param
     * @param bindingResult
     * @param model
     * @param request
     * @return
     */

    //开始预约导游 生成订单
    //先查看用户是否已经被预约
    @PostMapping("/approximately")
    @GuidelInterceptor
    public  @ResponseBody
    GuideResult approximately(@Validated GuideForm guideForm, BindingResult bindingResult, Model model, HttpServletRequest request){
//        因为前端验证的比较苛刻 所有后台验证并没有用的上 下面是实体类中出错的原因 没有进行实验
        List<FieldError> errorList =bindingResult.getFieldErrors();
        Map<String,String> map=new HashMap();
        if(null!=errorList &&errorList.size()>0){
            for(FieldError fieldError:errorList){
                //fieldError.getField()封装的是属性名称 getDefaultMessages属性名称的错误
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errorMaps",map);
            System.out.println("提交表单发生了错误，请查看表单中的值是否正确");
            return new GuideResult(GuideCodeStatus.ERROR,false,"表单提交错误");
        }else{
            HttpSession session=request.getSession();
            UserTable userTable= (UserTable) session.getAttribute("userId");
            GuideInfo apply= guideService.checkApply(userTable.getId());
            if(apply!=null&&apply.getId()==guideForm.getGuideId()){
                //自己申请自己
                return new GuideResult(GuideCodeStatus.NOTACCESS,false,"不可自己预约自己");
            }

            //先判断改用户的天数
            String applyTime= guideForm.getGoDate(); //获取出发日期字符串
            Date d= DateUtileDemo.parse("yyyy-MM-dd",applyTime);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(d);
            calendar.add(calendar.DATE, guideForm.getDays()-1);
            String endDay = DateUtileDemo.format("yyyy-MM-dd",calendar.getTime());  //获取截至日期字符串
            //转换成数据库的类型
            java.sql.Date sqlapplyTime= java.sql.Date.valueOf(applyTime); //开始申请的时间
            java.sql.Date sqlend= java.sql.Date.valueOf(endDay); //结束时间
            Integer guide_id=guideForm.getGuideId();//导游id

            //==============================================================改善
            Boolean flag= guideService.getOrderById(guide_id,applyTime,sqlend);
           if(flag==false){
               System.out.println("时间冲突");
               return new GuideResult(GuideCodeStatus.NOTACCESS,false,"时间冲突,导游不可预约");
           }else {

               Boolean flags=guideService.checkUserBill(userTable.getId(),applyTime);
               if(!flags){

                   return new GuideResult(GuideCodeStatus.NOTACCESS,false,"您以下单");
               }
               //--------------
//               else {
//                   Boolean count = guideService.checkUserBill(userTable.getId(),applyTime);
//                   Boolean flag2=guideService.checkUserBill(userTable.getId(),applyTime);
//                   if(!flag2){
//
//                       return new GuideResult(GuideCodeStatus.NOTACCESS,false,"您以下单");
//                   }
//               }
               //-----------

              String ord =String.valueOf(Random_util.getRandom()) ; //验证码

              Integer user_id=userTable.getId();//用户id
              Orders orders= new Orders();
              orders.setOrderno(ord);//设置验证码\
              orders.setUserId(userTable.getId());//设置userid
              Integer guiid= guideForm.getGuideId();//导游Id
              orders.setGuideId(guiid);
               //这个导游的居住地址 也就是旅行的目的地
               GuideIndex guideIndex= guideService.getPerosonById(guiid);
               String placce=guideIndex.getGuideApply().getCurrentAddress()+"市";
              orders.setPlace(placce);
              orders.setPhoneNumber(guideForm.getPhone());
              orders.setApplyName(guideForm.getUsername());
              orders.setPeopleSum(guideForm.getPeoples());
              orders.setDays(guideForm.getDays());
               MyOrders myOrders= new MyOrders();
               myOrders.setSqlend(sqlend);
               long t= worker.nextId();
               myOrders.setVerification(t);
               myOrders.setSqlapplyTime(sqlapplyTime);
               myOrders.setOrders(orders);
               Date date = new Date();
               String strDateFormat = "yyyy-MM-dd HH:mm:ss";
               SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
               String  ordertime= sdf.format(date);
               myOrders.setOrderTime(ordertime);
               guideService.inserOrders( myOrders);
               String tokens=  CreatToken.createToken("ok");//说明已经发送成功了
               //短信通知导游
               SmsModel.sendSms(guideIndex.getGuideApply().getGuidePhone(),441798,guideIndex.getGuideApply().getActualName());
               return new GuideResult(GuideCodeStatus.OK,true,"成功",tokens);
           }

        }

    }









}
